<template>
	<view class="settlement-container">
		<!-- 导航栏 -->
		<nav-bar></nav-bar>
		<!-- 标签页 -->
		<view class="tabs">
			<view class="tab-item" v-for="(tab, index) in tabs" :key="index" :class="{ active: currentTab === index }"
				@tap="switchTab(index)">
				{{ tab }}
			</view>
		</view>
		<!-- 时间筛选 -->
		<view class="time-filter">
			<view class="calendar-picker" @tap="showDatePicker">
				<text class="iconfont icon-calendar"></text>
				<text class="time-text">{{ this.timeOptions[timeType] }}</text>
				<text class="iconfont icon-down"></text>
			</view>
			<view class="amount-info">
				<text>待结算 ¥{{ totalAmountBeSettled }}</text>
				<text class="divider">|</text>
				<text>已结算 ¥{{ totalSettledAmount }}</text>
			</view>
		</view>
		<!-- 空状态 -->
		<view class="empty-state" v-if="!hasData">
			<image src="/static/empty-settlement.png" mode="aspectFit" class="empty-image"></image>
			<text class="empty-text">暂时还没有数据哦~</text>
		</view>
		<!-- 订单列表 -->
		<scroll-view v-else scroll-y class="order-list" @scrolltolower="loadMore">
			<view class="order-item"
				v-for="(order, index) in currentTab === 0 ? allList : currentTab === 1 ? pendingSettlementList: alreadySettledList"
				:key="index">
				<view class="order-header">
					<text class="order-no">订单号：{{ order.orderNo }}</text>
					<text class="order-status" :class="{ 'status-pending': order.orderStatus === 2 }">
						{{ order.orderStatus === 2 ? '待结算' : '已结算' }}
					</text>
				</view>
				<view class="order-content">
					<view class="service-info">
						<text class="service-name">{{ order.serviceName }}</text>
						<text class="service-price">¥{{ order.paymentAmount }}</text>
					</view>
					<view class="service-detail">
						<view class="detail-item">
							<text class="label">服务时间：</text>
							<text class="value">{{ order.appointmentDate+" "+order.appointmentTime }}</text>
						</view>
						<view class="detail-item">
							<text class="label">服务类型：</text>
							<text
								class="value">{{ order.orderType === 1 ? '预约到店' : order.orderType === 2 ? '上门按摩' : '未知类型' }}</text>
						</view>
						<view class="detail-item">
							<text class="label">服务技师：</text>
							<text class="value">{{ order.technicianName }}</text>
						</view>
					</view>
				</view>
			</view>
			<!-- 加载更多 -->
			<view class="loading-more" v-if="hasMore">
				<text>加载中...</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import NavBar from '@/components/nav-bar/nav-bar.vue';
	import {
		request
	} from '@/utils/request.js';
	export default {
		components: {
			NavBar
		},
		data() {
			return {
				allList: [],
				pendingSettlementList: [],
				alreadySettledList: [],
				totalAmountBeSettled: 0,
				totalSettledAmount: 0,
				tabs: ['全部', '待结算', '已结算'],
				currentTab: 0,
				timeType: 0,
				settledAmount: '0.00',
				pendingAmount: '0.00',
				hasData: false,
				hasMore: false,
				page: 1,
				orderList: [],
				timeOptions: ['本月', '上月', '近三个月'],
				commissionRate: 0, // 分成比例
				commissionInfo: null // 分成信息
			}
		},
		onLoad() {
			this.getData()
		},
		methods: {
			// 获取技师ID
			getData() {
				const userInfo = uni.getStorageSync('userInfo')
				if (!userInfo || !userInfo.techId) {
					uni.showToast({
						title: '请先登录',
						icon: 'error',
						duration: 2000
					});
					return
				}
				request({
					url: `${uni.$config.baseUrl}/orders/orders/get-settlement-order-list`,
					method: 'GET',
					data: {
						timeType: this.timeType + 1,
						techId: userInfo.techId
					}
				}).then(res => {
					this.allList = res.data.allList || []
					this.pendingSettlementList = res.data.pendingSettlementList || []
					this.alreadySettledList = res.data.alreadySettledList || []
					this.totalAmountBeSettled = res.data.totalAmountBeSettled || 0
					this.totalSettledAmount = res.data.totalSettledAmount || 0

					// 根据当前标签一次性判断是否有数据
					const listMap = [this.allList, this.pendingSettlementList, this.alreadySettledList];
					this.hasData = listMap[this.currentTab].length > 0;
				})
			},
			// 返回上一页
			goBack() {
				uni.navigateBack()
			},

			// 显示搜索页面
			showSearch() {
				// TODO: 实现搜索功能
				uni.showToast({
					title: '搜索功能开发中',
					icon: 'none'
				})
			},

			// 切换标签
			switchTab(index) {
				if (this.currentTab === index) return
				this.currentTab = index
				this.page = 1
				this.orderList = []
			},
			// 显示日期选择器
			showDatePicker() {
				uni.showActionSheet({
					itemList: this.timeOptions,
					success: ({
						tapIndex
					}) => {
						// 更新筛选项
						this.timeType = tapIndex;
						this.currentTab = 0;
						// 清空当前列表并隐藏数据，避免旧数据闪屏
						this.allList = [];
						this.pendingSettlementList = [];
						this.alreadySettledList = [];
						this.hasData = false;
						this.getData();
					}
				})
			},
			// 计算分成金额
			calculateCommissionAmount(amount) {
				if (!amount || !this.commissionRate) return 0
				// 计算分成金额并保留1位小数四舍五入
				return Math.round(amount * (this.commissionRate / 100) * 10) / 10
			},
			// 加载结算数据
			async loadSettlementData() {
				uni.showLoading({
					title: '加载中...'
				})
				try {
					const result = await uni.request({
						url: `${uni.$config.baseUrl}/orders/orders/listAll`,
						method: 'GET',
						data: {
							technicianId: this.techId,
							orderStatus: 3,
							paymentStatus: 1
						}
					})
					if (result.data.code === 200) {
						const orders = result.data.rows || []
						// 过滤掉已取消的订单（orderStatus为'4'的订单）
						const filteredOrders = orders.filter(order => order.orderStatus !== '4' && order
							.orderStatus !== 4)
						// 计算待结算和已结算金额
						let pendingAmount = 0
						let settledAmount = 0
						// 处理订单数据，添加分成金额
						const processedOrders = filteredOrders.map(order => {
							const paymentAmount = Number(order.paymentAmount || 0)
							const commissionAmount = this.calculateCommissionAmount(paymentAmount)
							// 添加分成金额到订单对象
							order.commissionAmount = commissionAmount
							if (order.paymentStatus === 0) {
								pendingAmount += commissionAmount
							} else if (order.paymentStatus === 1) {
								settledAmount += commissionAmount
							}
							return order
						})
						// 按创建时间倒序排序
						processedOrders.sort((a, b) => {
							const timeA = new Date(a.createTime || a.createDate || 0).getTime()
							const timeB = new Date(b.createTime || b.createDate || 0).getTime()
							return timeB - timeA
						})
						this.settledAmount = settledAmount.toFixed(2)
						this.pendingAmount = pendingAmount.toFixed(2)
						// 根据当前标签筛选订单
						if (this.currentTab === 1) {
							this.orderList = processedOrders.filter(order => order.paymentStatus === 0)
						} else if (this.currentTab === 2) {
							this.orderList = processedOrders.filter(order => order.paymentStatus === 1)
						} else {
							this.orderList = processedOrders
						}
						this.hasData = this.orderList.length > 0
						this.hasMore = false // 由于是一次性获取所有数据，所以没有更多数据
					}
				} catch (err) {
					uni.showToast({
						title: '获取数据失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			},
			// 加载更多
			loadMore() {
				if (this.hasMore) {
					this.page++
					this.loadSettlementData()
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.settlement-container {
		min-height: 100vh;
		background: #F5F5F5;

		.custom-nav-bar {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			height: 88rpx;
			background: #FFFFFF;
			display: flex;
			align-items: center;
			padding: 0 30rpx;
			z-index: 100;

			.left,
			.right {
				width: 88rpx;
				display: flex;
				align-items: center;

				.iconfont {
					font-size: 40rpx;
					color: #333333;
				}
			}

			.center {
				flex: 1;
				text-align: center;
				font-size: 36rpx;
				color: #333333;
				font-weight: 500;
			}
		}

		.tabs {
			position: fixed;
			left: 0;
			right: 0;
			height: 3%;
			background: #FFFFFF;
			display: flex;
			justify-content: space-around;
			align-items: center;
			z-index: 99;
			box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

			.tab-item {
				position: relative;
				padding: 24rpx 0;
				font-size: 32rpx;
				color: #666666;
				transition: all 0.3s ease;

				&.active {
					color: #2B87FF;
					font-weight: 500;
				}
			}
		}

		.time-filter {
			position: fixed;
			top: 100rpx;
			left: 0;
			right: 0;
			padding-top: 6%;
			padding-left: 3%;
			padding-right: 3%;
			background: #FFFFFF;
			z-index: 98;
			display: flex;
			justify-content: space-between;
			align-items: center;
			border-bottom: 1rpx solid #F0F0F0;

			.calendar-picker {
				display: flex;
				align-items: center;
				padding: 12rpx 20rpx;
				background: #F8F8F8;
				border-radius: 30rpx;
				transition: all 0.3s ease;

				&:active {
					background: #F0F0F0;
				}

				.iconfont {
					font-size: 36rpx;
					color: #666666;
					margin-right: 10rpx;

					&.icon-down {
						font-size: 28rpx;
						margin-left: 10rpx;
						margin-right: 0;
					}
				}

				.time-text {
					font-size: 32rpx;
					color: #333333;
				}
			}

			.amount-info {
				font-size: 28rpx;
				color: #666666;

				.divider {
					margin: 0 20rpx;
					color: #DDDDDD;
				}
			}
		}

		.commission-info {
			position: fixed;
			top: 200rpx;
			left: 0;
			right: 0;
			padding: 20rpx 30rpx;
			background: #FFFFFF;
			z-index: 97;
			border-bottom: 1rpx solid #EEEEEE;

			.commission-rate {
				font-size: 28rpx;
				color: #2B85E4;
				font-weight: 500;
			}
		}

		.empty-state {
			position: fixed;
			top: 176rpx;
			left: 0;
			right: 0;
			bottom: 0;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;

			.empty-image {
				width: 400rpx;
				height: 400rpx;
				margin-bottom: 30rpx;
			}

			.empty-text {
				font-size: 32rpx;
				color: #999999;
			}
		}

		.order-list {
			height: 94%;
			position: fixed;
			padding-top: 15%;
			left: 0;
			right: 0;
			background: #ffffff;

			.loading-more {
				text-align: center;
				padding: 30rpx 0;
				font-size: 28rpx;
				color: #999999;
			}
		}
	}

	.order-item {
		margin: 24rpx;
		background: #FFFFFF;
		border-radius: 16rpx;
		padding: 36rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.03);
		transition: transform 0.3s ease;

		&:active {
			transform: scale(0.98);
		}

		.order-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 24rpx;
			border-bottom: 1rpx solid #F5F5F5;
			padding-bottom: 20rpx;

			.order-no {
				font-size: 30rpx;
				color: #666666;
			}

			.order-status {
				font-size: 30rpx;
				color: #2B87FF;
				font-weight: 500;
				padding: 6rpx 16rpx;
				background: rgba(43, 135, 255, 0.1);
				border-radius: 20rpx;

				&.status-pending {
					color: #FF9900;
					background: rgba(255, 153, 0, 0.1);
				}
			}
		}

		.order-content {
			.service-info {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 24rpx;

				.service-name {
					font-size: 36rpx;
					color: #333333;
					font-weight: 500;
				}

				.service-price {
					font-size: 36rpx;
					color: #2B87FF;
					font-weight: 500;
				}
			}

			.service-detail {
				background: #F8F8F8;
				border-radius: 12rpx;
				padding: 20rpx;

				.detail-item {
					display: flex;
					margin-bottom: 12rpx;

					&:last-child {
						margin-bottom: 0;
					}

					.label {
						font-size: 30rpx;
						color: #999999;
						width: 160rpx;
					}

					.value {
						font-size: 30rpx;
						color: #333333;
						flex: 1;
					}

					.commission-amount {
						color: #2B87FF;
						font-weight: 500;
					}
				}
			}
		}
	}
</style>